from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field, ConfigDict

from app.models import get_db
from app.services.permission_service import PermissionService
from app.utils.response import Response

router = APIRouter(prefix="/permissions", tags=["权限管理"])

# 请求模型
class PermissionCreate(BaseModel):
    """权限创建请求模型"""
    name: str = Field(..., description="权限名称", example="用户管理")
    code: str = Field(..., description="权限编码", example="user:manage")
    description: Optional[str] = Field(None, description="权限描述", example="用户管理模块权限")
    parent_id: Optional[int] = Field(None, description="父权限ID")
    is_menu: Optional[bool] = Field(False, description="是否为菜单项")
    path: Optional[str] = Field(None, description="前端路由路径", example="/user")
    component: Optional[str] = Field(None, description="前端组件路径", example="@/views/UserManage")
    icon: Optional[str] = Field(None, description="图标", example="user")
    sort_order: Optional[int] = Field(0, description="排序序号")

class PermissionUpdate(BaseModel):
    """权限更新请求模型"""
    name: Optional[str] = Field(None, description="权限名称", example="用户管理")
    code: Optional[str] = Field(None, description="权限编码", example="user:manage")
    description: Optional[str] = Field(None, description="权限描述", example="用户管理模块权限")
    parent_id: Optional[int] = Field(None, description="父权限ID")
    is_menu: Optional[bool] = Field(None, description="是否为菜单项")
    path: Optional[str] = Field(None, description="前端路由路径", example="/user")
    component: Optional[str] = Field(None, description="前端组件路径", example="@/views/UserManage")
    icon: Optional[str] = Field(None, description="图标", example="user")
    sort_order: Optional[int] = Field(None, description="排序序号")

class PermissionOut(BaseModel):
    """权限输出模型"""
    id: int = Field(..., description="权限ID")
    name: str = Field(..., description="权限名称")
    code: str = Field(..., description="权限编码") 
    description: Optional[str] = Field(None, description="权限描述")
    parent_id: Optional[int] = Field(None, description="父权限ID")
    is_menu: bool = Field(..., description="是否为菜单项")
    path: Optional[str] = Field(None, description="前端路由路径")
    component: Optional[str] = Field(None, description="前端组件路径")
    icon: Optional[str] = Field(None, description="图标")
    sort_order: int = Field(..., description="排序序号")

    model_config = ConfigDict(from_attributes=True)

class RolePermissionRequest(BaseModel):
    """角色权限关联请求模型"""
    role_id: int = Field(..., description="角色ID")
    permission_id: int = Field(..., description="权限ID")

# API接口
@router.post("", response_model=dict)
def create_permission(permission_data: PermissionCreate, db: Session = Depends(get_db)):
    """创建权限"""
    permission = PermissionService.create_permission(
        db,
        name=permission_data.name,
        code=permission_data.code,
        description=permission_data.description,
        parent_id=permission_data.parent_id,
        is_menu=permission_data.is_menu,
        path=permission_data.path,
        component=permission_data.component,
        icon=permission_data.icon,
        sort_order=permission_data.sort_order
    )
    return Response.success(PermissionOut.model_validate(permission))

@router.get("", response_model=dict)
def get_permission_list(db: Session = Depends(get_db)):
    """获取权限列表"""
    permissions = PermissionService.get_permission_list(db)
    result = [PermissionOut.model_validate(perm) for perm in permissions]
    return Response.success(result)

@router.get("/tree", response_model=dict)
def get_permission_tree(db: Session = Depends(get_db)):
    """获取权限树结构"""
    tree = PermissionService.get_permission_tree(db)
    return Response.success(tree)

@router.get("/{permission_id}", response_model=dict)
def get_permission(permission_id: int, db: Session = Depends(get_db)):
    """获取权限详情"""
    permission = PermissionService.get_permission_by_id(db, permission_id)
    return Response.success(PermissionOut.model_validate(permission))

@router.put("/{permission_id}", response_model=dict)
def update_permission(permission_id: int, permission_data: PermissionUpdate, db: Session = Depends(get_db)):
    """更新权限信息"""
    # 过滤掉None值
    update_data = {k: v for k, v in permission_data.model_dump().items() if v is not None}
    permission = PermissionService.update_permission(db, permission_id, **update_data)
    return Response.success(PermissionOut.model_validate(permission))

@router.delete("/{permission_id}", response_model=dict)
def delete_permission(permission_id: int, db: Session = Depends(get_db)):
    """删除权限"""
    PermissionService.delete_permission(db, permission_id)
    return Response.success({"message": f"权限 {permission_id} 已删除"})

@router.post("/assign", response_model=dict)
def assign_permission_to_role(data: RolePermissionRequest, db: Session = Depends(get_db)):
    """为角色分配权限"""
    PermissionService.assign_permission_to_role(db, data.role_id, data.permission_id)
    return Response.success({"message": f"已成功为角色 {data.role_id} 分配权限 {data.permission_id}"})

@router.post("/remove", response_model=dict)
def remove_permission_from_role(data: RolePermissionRequest, db: Session = Depends(get_db)):
    """从角色移除权限"""
    PermissionService.remove_permission_from_role(db, data.role_id, data.permission_id)
    return Response.success({"message": f"已成功从角色 {data.role_id} 移除权限 {data.permission_id}"})

@router.get("/role/{role_id}", response_model=dict)
def get_role_permissions(role_id: int, db: Session = Depends(get_db)):
    """获取角色拥有的权限"""
    permissions = PermissionService.get_role_permissions(db, role_id)
    result = [PermissionOut.model_validate(perm) for perm in permissions]
    return Response.success(result)
